package com.intexh.quickandroid.module.chat.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author Milk (QQ: 249828165)
 *         时间日期处理类
 */
public class DateUtil {
    public final static String TAG = "DateUtil";
    public final static String[] WEEK_DAYS = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
    public final static String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static long getUnixTime() {
        return System.currentTimeMillis() / 1000L;
    }

    public static String getTimestamp() {
        return DateFormatUtils.format(System.currentTimeMillis(), DEFAULT_FORMAT);
    }

    public static long startOfDay() {
        return startOfDay(new Date());
    }

    public static long startOfDay(String time) {
        return startOfDay(strToTime(time));
    }

    public static long startOfDay(long time) {
        final Calendar dCal = Calendar.getInstance();
        dCal.setTimeInMillis(time);
        dCal.set(Calendar.HOUR_OF_DAY, 0);
        dCal.set(Calendar.MINUTE, 0);
        dCal.set(Calendar.SECOND, 0);
        dCal.set(Calendar.MILLISECOND, 0);

        return dCal.getTimeInMillis();
    }

    public static long startOfDay(Date date) {
        final Calendar dCal = Calendar.getInstance();
        dCal.setTime(date);
        dCal.set(Calendar.HOUR_OF_DAY, 0);
        dCal.set(Calendar.MINUTE, 0);
        dCal.set(Calendar.SECOND, 0);
        dCal.set(Calendar.MILLISECOND, 0);

        return dCal.getTimeInMillis();
    }

    public static long strToTime_2(String ts) {
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return mSimpleDateFormat.parse(ts).getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static long strToTime(String ts) {
        String format = "";
        if (ts.length() == 21 && ts.endsWith(".0")) { //2012-10-13 10:08:01.0
            format = DEFAULT_FORMAT;
            ts = ts.substring(0, ts.length() - 2);
        } else if (ts.length() == 19) {
            format = DEFAULT_FORMAT;
        } else if (ts.length() == 10) {
            format = "yyyy-MM-dd";
        } else {
            return 0;
        }
//        else throw new Exception("TimeUtils::strToTime无法转换时间：" + ts);

        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
        try {
            return mSimpleDateFormat.parse(ts).getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static String getDate(long ts) {
        return date("yyyy-MM-dd", ts);
    }

    public static String getDateAndTime(long ts) {
        return date("yyyy-MM-dd HH:mm", ts);
    }

    public static String getDate_3(long ts) {
        return date("yyyy.MM.dd", ts);
    }

    public static String getChineseDate(long ts){
        return  date("yyyy年M月d日", ts);
    }


    public static String getDateMD(long ts) {
        return date("M.dd", ts);
    }

    public static String getTimeHM(long ts) {
        return date("hh:mm", ts);
    }
    public static String getTimeHM_24(long ts) {
        return date("HH:mm", ts);
    }
    
    public static String getTimeMS(long ts) {
        return date("mm:ss", ts);
    }

    public static String getDateTime(long ts) {
        return date("yyyy/MM/dd/HH:mm", ts);
    }
    public static String getYear(long ts) {
        return date("yyyy", ts);
    }

    public static String getDateStr(long ts) {
        return date(DEFAULT_FORMAT, ts);
    }

    public static String getDateStr(String ts) {
        // 处理2012-01-01 01:01:01.0的情况
        if (ts.endsWith(".0")) {
            return ts.substring(0, ts.length() - 2);
        } else {
            return ts;
        }
    }

    public static String date(String format) {
        return DateFormatUtils.format(System.currentTimeMillis(), format);
    }

    public static String date(String format, long ts) {
        return DateFormatUtils.format(ts, format);
    }

    public static String getMonday(String ts) throws Exception {
        if ("".equals(ts) || "0000-00-00".equals(ts)) return "0000-00-00";
        else return getMonday(strToTime(ts));
    }

    //日期转时间戳
    public static String getTime(String timeString,String format){//
        String timeStamp = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d;
        try{
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l);
        } catch(Exception e){
            e.printStackTrace();
        }
        return timeStamp;
    }

    //日期转时间戳
    public static String getTimeToSeconds(String timeString,String format){//
        String timeStamp = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d;
        try{
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l/1000);
        } catch(Exception e){
            e.printStackTrace();
        }
        return timeStamp;
    }

    /**
     * 获取一周的开始星期一的日期
     *
     * @param ts long
     * @return string Y-m-d
     */
    public static String getMonday(long ts) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(ts);
        c.setFirstDayOfWeek(Calendar.MONDAY);
        // Set the calendar to monday of the current week
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        // Print dates of the current week starting on Monday
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(c.getTime());
    }

    /**
     * 根据年份和周数返回该周一的日期
     *
     * @param year
     * @param week_num
     * @return Y-m-d
     * @throws Exception
     */
    public static String getWeekMonday(int year, int week_num) throws Exception {
        int week_sec = 7 * 24 * 3600;
        //周数的星期天的日期
        long et = strToTime(year + "-01-01") + week_num * week_sec;
        return getDate(et - week_sec);
    }

    /**
     * 获取当前日期是星期几
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(long dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dt);
        return getWeekOfDate(cal);
    }

    public static String getWeekOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        return getWeekOfDate(cal);
    }

    public static String getWeekOfDate(Calendar cal) {
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) w = 0;

        return WEEK_DAYS[w];
    }

    /**
     * 该时间是否为今天
     *
     * @param datetime
     * @return
     */
    public static boolean isToday(String datetime) {
        String today = getDate(System.currentTimeMillis());
        return today.equals(datetime.substring(0, today.length()));
    }

    public static class Constellation {
        public static final String[] zodiacArr = {"猴", "鸡", "狗", "猪", "鼠", "牛",
                "虎", "兔", "龙", "蛇", "马", "羊"};

        public static final String[] constellationArr = {"水瓶", "双鱼", "牡羊",
                "金牛", "双子", "巨蟹", "狮子", "处女", "天秤", "天蝎", "射手", "魔羯"};

        public static final int[] constellationEdgeDay = {20, 19, 21, 21, 21, 22,
                23, 23, 23, 23, 22, 22};

        /**
         * 根据日期获取生肖
         *
         * @return
         */
        public static String date2Zodica(Calendar time) {
            return zodiacArr[time.get(Calendar.YEAR) % 12];
        }

        /**
         * 根据日期获取星座
         *
         * @param time
         * @return
         */
        public static String date2Constellation(Calendar time) {
            int month = time.get(Calendar.MONTH);
            int day = time.get(Calendar.DAY_OF_MONTH);
            if (day < constellationEdgeDay[month]) {
                month = month - 1;
            }
            if (month >= 0) {
                return constellationArr[month];
            }
            // default to return 魔羯
            return constellationArr[11];
        }
    }

    public static String getTimeAMorPm(long time) {
        GregorianCalendar ca = new GregorianCalendar();
        ca.setTime(new Date(time));
        if (ca.get(GregorianCalendar.AM_PM) > 0) {
            return "pm";
        } else {
            return "am";
        }
    }

    public static String getDefaultDateTime(long time) {
        long st = startOfDay();
        if (time >= st && time < st + 24 * 3600 * 1000)
            return "今天";

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        StringBuilder sb = new StringBuilder();
        sb.append(cal.get(Calendar.MONTH) + 1).append("月")
                .append(cal.get(Calendar.DATE)).append("日 ")
                .append(getWeekOfDate(cal));

        return sb.toString();
    }
    public static String encounterRecordDateMonth(long millisTime) {
        return date("M", millisTime);
    }

    public static String encounterRecordDate(long millisTime) {
        return date("M.dd", millisTime);
    }
    
    public static String separatorDate(long millisTime) {
        return date("MM-dd", millisTime);
    }
    
    public static String timeMachineDate(long millisTime) {
        return date("yyyy/MM/dd", millisTime);
    }
    
    public static String encounterRecordMonth(long millisTime) {
        return date("M", millisTime)+"月";
    }
    
    public static String encounterRecordTime(long millisTime) {
        return date("h:mmaa", millisTime);
    }

    public static String time(long millisTime) {
        return date("HH:mm", millisTime);
    }
    
    public static String holdDate(long millisTime) {
        return date("yyyy-MM-dd", millisTime);
    }
    
    public static String trackDate(long millisTime) {
        return date("yyyy.MM.dd", millisTime);
    }
    
    public static String encounterTime(long millisTime) {
        long intervalSinceNow = abs((System.currentTimeMillis() - millisTime) / 1000);
        long todayBeginning = startOfDay() / 1000;
        long intervalSinceToday = todayBeginning - millisTime / 1000;

        if (intervalSinceNow < 60)
            return "刚刚";
        else if (intervalSinceNow < 3600)
            return (intervalSinceNow / 60) + "分钟前";
        else if (intervalSinceToday < 0)
            return (intervalSinceNow / 3600) + "小时前";
        else if (intervalSinceNow < 31536000) //86400 * 360
            return date("M月d日 H:mm", millisTime);
        else
            return date("yyyy年M月d日 H:mm", millisTime);
    }

    public static String postTime(long millisTime) {
        long intervalSinceNow = abs((System.currentTimeMillis() - millisTime) / 1000);
        long todayBeginning = startOfDay() / 1000;
        long intervalSinceToday = todayBeginning - millisTime / 1000;

        if (intervalSinceNow < 60)
            return "刚刚";
        else if (intervalSinceNow < 3600)
            return (intervalSinceNow / 60) + "分钟前";
        else if (intervalSinceNow < 14400)
            return (intervalSinceNow / 3600) + "小时前";
        else if (intervalSinceToday < 0)
            return date("H:mm", millisTime);
        else if (intervalSinceToday < 86400)
            return "昨天 " + date("H:mm", millisTime);
        else if (intervalSinceToday < 2592000)  //86400 * 30
            return (intervalSinceToday / 86400) + 1 + "天前";
        else if (intervalSinceNow < 31536000) //86400 * 360
            return date("MM - dd", millisTime);
        else
            return date("yyyy - MM - dd", millisTime);
    }

    public static String postTime_3_5(long millisTime) {
        long intervalSinceNow = abs((System.currentTimeMillis() - millisTime) / 1000);
        long todayBeginning = startOfDay() / 1000;
        long intervalSinceToday = todayBeginning - millisTime / 1000;

        if (intervalSinceNow < 60)
            return "今天";
        else if (intervalSinceNow < 3600)
            return "今天";
        else if (intervalSinceNow < 14400)
            return "今天";
        else if (intervalSinceToday < 0)
            return "今天";
        else if (intervalSinceToday < 86400)
            return "昨天";
        else if (intervalSinceToday < 2592000)  //86400 * 30
            return date("MM月dd日", millisTime);
        else if (intervalSinceNow < 31536000) //86400 * 360
            return date("MM月dd日", millisTime);
        else
            return date("yyyy年MM月dd日", millisTime);
    }

    public static String notificationTime(long millisTime) {
        return date("M月d日 h:mmaa", millisTime);
    }

    public static String sessionTime(long millisTime) {
        long intervalSinceNow = abs((System.currentTimeMillis() - millisTime) / 1000);
        long todayBeginning = startOfDay() / 1000;
        long intervalSinceToday = todayBeginning - millisTime / 1000;

        if (intervalSinceToday < 0)
            return date("H:mm", millisTime);
        else if (intervalSinceToday < 86400)
            return "昨天";
        else if (intervalSinceToday < 86400 * 3)
            return getWeekOfDate(millisTime);
        else if (intervalSinceNow < 31536000) //86400 * 360
            return date("M月d日 H:mm", millisTime);
        else
            return date("yyyy年M月d日 H:mm", millisTime);
    }


    public static String chatTime(long millisTime) {
        long intervalSinceNow = abs((System.currentTimeMillis() - millisTime) / 1000);
        long todayBeginning = startOfDay() / 1000;
        long intervalSinceToday = todayBeginning - millisTime / 1000;

        if (intervalSinceToday < 0)
            return date("H:mm", millisTime);
        else if (intervalSinceToday < 86400)
            return "昨天 " + date("H:mm", millisTime);
        else if (intervalSinceToday < 86400 * 3)
            return getWeekOfDate(millisTime) + " " + date("H:mm", millisTime);
        else if (intervalSinceNow < 31536000) //86400 * 360
            return date("M月d日 H:mm", millisTime);
        else
            return date("yyyy年M月d日 H:mm", millisTime);
    }

    public static String timeMachineRecordTime(long millisTime)
    {
        long intervalSinceNow = abs((System.currentTimeMillis() - millisTime) / 1000);
        String result;
        if (intervalSinceNow < 60)
        	result = "刚刚";
        else if (intervalSinceNow < 3600)
        	result = (intervalSinceNow / 60) + "分钟前";
        else if (intervalSinceNow < 86400)
        	result = (intervalSinceNow / 3600) + "小时前";
        else if (intervalSinceNow < 604800)
        	result = (intervalSinceNow / 86400) +"天前";
        else if (intervalSinceNow < 2592000)
        	result = (intervalSinceNow / 604800) + "周前";
        else if (intervalSinceNow < 31536000)
        	result = (intervalSinceNow / 2592000) + "个月前";
        else
        	result = (intervalSinceNow / 31536000) +"年前";
        return result;
    }
    
    /**
     * 将传进来的秒数格式化为“00:00”的形式
     * @param time	单位毫秒
     * @return
     */
    public static String secondToTime(long time){
        time /= 1000;
        String timeStr = null;
        long minute = 0;
        long second = 0;

        if(time <= 0){
            return "00:00";
        }else{
            minute = time / 60;
            second = time % 60;
            timeStr = timeFormat(minute)+":"+timeFormat(second);
        }

        return timeStr;
    }

    public static String secondToTime_2(long time){
        time /= 1000;
        String timeStr = null;
        long minute = 0;
        long second = 0;
        long hour=0;

        if(time <= 0){
            return "00:00:00";
        }else{
            hour=time/3600;
            minute = time%3600/60;
            second = time % 60;
            timeStr = timeFormat(hour)+":"+timeFormat(minute)+":"+timeFormat(second);
        }

        return timeStr;
    }
	
	private static String timeFormat(long time) {
		String str = null;
		if(time >= 0 && time<10){
			str = "0" + String.valueOf(time);
		}else{
			str = "" + time; 
		}
		return str;
	}
    
    private static long abs(long value) {
        if (value < 0) {
            value *= -1;
        }
        return value;
    }
    /**
     *
     * **/
    public static long getDateTimestamp(long time){
        String dateStr=getDate(time);
        Date date = new Date();
        //注意format的格式要与日期String的格式相匹配
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = sdf.parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static long getTimeTimestamp(String dateStr){
        Date date = new Date();
        //注意format的格式要与日期String的格式相匹配
        DateFormat sdf = new SimpleDateFormat("hh:mm");
        try {
            date = sdf.parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static String getTimeLeft(long endTime){
        if(endTime > System.currentTimeMillis()){
            long timeLeft = endTime - System.currentTimeMillis();
            long dayLeft = timeLeft/1000/60/60/24;
            return "还剩"+dayLeft+"天";
        }else{
            return "已结束";
        }
    }

    public static String getTimeMinLeft(long endTime){
        if(endTime > System.currentTimeMillis()){
            long timeLeft = endTime - System.currentTimeMillis();
            long dayLeft = timeLeft/1000/60/60;
            return "还剩"+dayLeft+"天";
        }else{
            return "已结束";
        }
    }

}
